import {Form, Toast, Cell, Field, Button, Input, Uploader, Textarea} from "@taroify/core";
import { BaseEventOrig, FormProps, View } from "@tarojs/components";
import { chooseImage } from "@tarojs/taro";
import { FormItemInstance } from "@taroify/core/form";
import { useRef } from "react";

export default function Create() {
  // 用于处理表单提交事件
  const onSubmit = (event: BaseEventOrig<FormProps.onSubmitEventDetail>) => {
    // 提交成功时打开 Toast，显示表单数据
    Toast.open(JSON.stringify(event.detail.value));
  };

  // 引用，用于获取上传控件的值
  const itemRef = useRef<FormItemInstance>();

  // 上传图片处理函数
  function onUpload() {
    chooseImage({
      count: 1,
      sizeType: ["original", "compressed"], // 图片类型
      sourceType: ["album", "camera"], // 图片来源
    }).then(({ tempFiles }) => {
      // 设置图片上传后的值
      itemRef.current?.setValue([
        ...(itemRef.current?.getValue() ? [...itemRef.current?.getValue()] : []),
        {
          url: tempFiles[0].path,
          type: tempFiles[0].type,
          name: tempFiles[0].originalFileObj?.name,
        },
      ]);
    });
  }

  return (
    <Form onSubmit={onSubmit}>
      {/* Toast 提示 */}
      <Toast id='toast' />

      {/* 表单内容区域 */}
      <Cell.Group inset>
        {/* 头像上传 */}
        <Field name='cover_image' label='封面图片' ref={itemRef}>
          <Uploader multiple onUpload={onUpload} />
        </Field>

        {/* 名称输入 */}
        <Field
          name='name'
          label={{ align: "left", children: "名称" }}
          rules={[{ required: true, message: "请填写名称" }]}
        >
          <Input placeholder='请输入名称' />
        </Field>

        {/* 描述输入 */}
        <Field
          name='description'
          label={{ align: "left", children: "描述" }}
          rules={[{ required: true, message: "请填写描述" }]}
        >
          <Textarea autoHeight placeholder='请输入描述' />
        </Field>

      </Cell.Group>

      {/* 提交按钮 */}
      <View style={{ margin: "16px" }}>
        <Button shape='round' block color='primary' formType='submit'>
          提交
        </Button>
      </View>
    </Form>
  );
}
